<template>
	<view class="promotion-container">
		<view class="rules-warps">
			<!-- 推广费规则部分 -->
			<view class="rules-section">
				<view class="section-title">推广费规则</view>
				<view class="rule-item">
					<text class="rule-number">1.</text>
					<text class="rule-text">推广成员作为乘客行程完成，车主支付信息费后可获得乘客行程信息费10%的推广费</text>
				</view>
				<view class="rule-item">
					<text class="rule-number">2.</text>
					<text class="rule-text">推广成员作为车主行程完成，支付信息费后可获得车主行程信息费10%的推广费</text>
				</view>
				<view class="rule-item">
					<text class="rule-number">3.</text>
					<text class="rule-text">用户推广费实时发放至授权微信零钱</text>
				</view>
				<view class="rule-item">
					<text class="rule-number">4.</text>
					<text class="rule-text">若账号封禁，封禁期间不可获取推广成员产生推广费</text>
				</view>
			</view>

			<!-- 推广成员获取规则 -->
			<view class="rules-section">
				<view class="section-title">推广费规则</view>
				<view class="rule-item">
					<text class="rule-number">1.</text>
					<text class="rule-text">新用户通过您的专属推广海报识别二维码进入拼车平台注册并关注公众号的将成为您的推广成员</text>
				</view>
				<view class="rule-item">
					<text class="rule-number">2.</text>
					<text class="rule-text">新用户通过您分享的行程链接进入拼车平台注册并关注公众号的将成为您的推广成员</text>
				</view>
			</view>

			<!-- <view class="rules-section">
				<view class="section-title">我的推广码</view>
				<view class="" style="display: flex; justify-content: center; padding-top: 40rpx">
					<ikun-qrcode width="250" height="250" unit="rpx" color="#000000" :data="code" />
				</view>
			</view> -->
		</view>

		<!-- 推广成员列表 -->
		<view class="member-list">
			<view class="member-title">推广费成员</view>
			<view v-if="members.length > 0" class="member-item" v-for="(member, index) in members" :key="index">
				<view class="member-info">
					<image v-if="member.avatar_full" :src="member.avatar_full" mode="aspectFill" class="member-header"></image>
					<image v-else src="/static/personalCenter/avatar.png" mode="aspectFill" class="member-header"></image>
					<view>
						<view class="member-name">{{ member.nickname }}</view>
						<view class="member-phone">{{ member.phone }}</view>
					</view>
				</view>
				<view class="member-fee">
					<view class="member-fee-value">
						<text>￥</text>
						{{ member.promotion_amount }}
					</view>
					<view class="member-fee-label">产生推广费</view>
				</view>
			</view>
			<empty-data v-if="members.length == 0" defaultText="暂无数据" />
		</view>

		<!-- 底部操作按钮 -->
		<view class="action-buttons">
			<view class="action-btn" @click="viewPoster">
				<image src="/static/personalCenter/wechat.png" mode="aspectFill"></image>
				<view class="action-btn-label">查看海报</view>
			</view>
			<view class="action-btn" @click="generatePoster">
				<image src="/static/personalCenter/download.png" mode="aspectFill"></image>
				<view class="action-btn-label">保存海报</view>
			</view>
			<view class="action-btn" @click="sharePoster">
				<image src="/static/personalCenter/share.png" mode="aspectFill"></image>
				<view class="action-btn-label">分享海报</view>
			</view>
		</view>
		<promotion-popup :visible.sync="showPopup" @update:visible="updateVisible" />
		<!-- 海报内容 -->
		<view class="popup-container" id="posterContainer" v-show="true">
			<view class="popup-content">
				<view class="code-container">
					<view class="qr-code-warps">
						<!-- <image src="/static/official-account.jpg" mode="aspectFill"></image> -->
						<ikun-qrcode width="200" height="200" unit="rpx" color="#000000" :data="code" />
						<!-- <view class="qr-code" id="qrcodeid"></view> -->
					</view>
					<view class="tips">
						<view>在微信扫一扫识别进入拼车平</view>
						<view>台注册并关注公众号</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 新增：海报图片弹窗 -->
		<view v-if="showPosterImage" class="poster-image-popup">
			<image :src="posterImageUrl" mode="widthFix" style="width: 80vw" @longpress="savePosterToAlbum"></image>
			<view class="popup-actions">
				<button class="popup-actions-btn" @click="savePosterToAlbum">保存到相册</button>
				<button class="popup-actions-btn" @click="showPosterImage = false">关闭</button>
			</view>
			<view class="popup-tip">如无法自动保存，请长按图片手动保存</view>
		</view>
	</view>
</template>

<script>
import promotionPopup from '../../common/promotionPostersPopup.vue';
import QRCode from 'qrcodejs2';
import html2canvas from 'html2canvas';
export default {
	components: {
		promotionPopup
	},
	data() {
		return {
			showPopup: false,
			members: [],
			page: 1,
			size: 20,
			posterImageUrl: '',
			showPosterImage: false, // 控制图片弹窗
			shareOptions: {
				title: '拼车出行更方便',
				desc: '快来加入我们的拼车平台，绿色出行更便捷！',
				link: 'https://carpool.mszcdf.cn/#/',
				imgUrl: ''
			},
			code: ''
		};
	},
	onLoad() {
		const app = getApp();
		let sharePrefix = app.platform === 'ios' ? uni.getStorageSync('firstIosUrl') : window.location.href.split('#')[0];
		let link = `${sharePrefix}${window.location.hash}`;
		if (link.includes('?')) {
			link = `${link}&pid=${uni.getStorageSync('userInfo').id}`;
		} else {
			link = `${link}?pid=${uni.getStorageSync('userInfo').id}`;
		}

		this.code = link;

		this.getMyPromotion();
	},
	methods: {
		async getMyPromotion() {
			let params = {
				page: this.page,
				size: this.size
			};
			try {
				const data = await this.$http.get('/h5/user/myPromotion', params);
				console.log('我的推广:', data.data);
				this.members = data.data.list;
			} catch (error) {}
		},
		updateVisible() {
			this.showPopup = false;
		},
		// 查看
		viewPoster() {
			this.showPopup = true;
		},
		// 生成二维码
		generateQRCode() {
			const qrcodeElement = document.getElementById('qrcodeid');
			qrcodeElement.innerHTML = '';
			new QRCode(qrcodeElement, {
				text: 'https://carpool.mszcdf.cn',
				width: 100,
				height: 100,
				colorDark: '#000000',
				colorLight: '#ffffff',
				correctLevel: QRCode.CorrectLevel.H
			});
		},

		// 生成海报
		async generatePoster() {
			if (this.posterImageUrl) {
				this.showPosterImage = true; // 新增：展示图片弹窗
				return;
			}

			console.log(1111111111111111);
			uni.showLoading({ title: '生成中...', mask: true });
			setTimeout(async () => {
				const container = document.getElementById('posterContainer');
				const canvas = await html2canvas(container, {
					// backgroundColor: '#ffffff',
					scale: 2,
					useCORS: true,
					allowTaint: true,
					logging: true,
					ignoreElements: (e) => {
						if (e.contains(container) || container.contains(e) || e.getAttribute('data-html2canvas') != null) {
							return false;
						}
						return true;
					}
				});
				// const blob = await new Promise((resolve, reject) => {
				// 	canvas.toBlob(
				// 		(blob) => {
				// 			if (!blob) {
				// 				reject(new Error('Canvas转换Blob失败'));
				// 				return;
				// 			}
				// 			resolve(blob);
				// 		},
				// 		'image/png',
				// 		1
				// 	);
				// });
				const base64Img = canvas.toDataURL('image/png');
				console.log(base64Img, '**************');

				// if (!(blob instanceof Blob)) {
				// 	throw new Error('生成的Blob对象无效');
				// }
				// const objectUrl = URL.createObjectURL(blob);
				// console.log(objectUrl, '*********');
				// if (!objectUrl || typeof objectUrl !== 'string') {
				// 	throw new Error('创建对象URL失败');
				// }
				this.posterImageUrl = base64Img;
				this.showPosterImage = true; // 新增：展示图片弹窗
				uni.hideLoading();
			}, 500);
		},
		async savePosterToAlbum() {
			// #ifdef H5
			uni.showToast({ title: '请长按图片保存到相册', icon: 'none' });
			// #endif
			// #ifndef H5
			try {
				// 检查是否有图片URL
				if (!this.posterImageUrl) {
					uni.showToast({ title: '请先生成海报', icon: 'none' });
					return;
				}
				// 调用微信保存图片接口
				wx.ready(() => {
					wx.downloadImage({
						serverId: '', // 这里不需要
						isShowProgressTips: 1,
						success: (res) => {
							const localId = res.localId;
							wx.saveImageToPhotosAlbum({
								localId: localId,
								success: () => {
									uni.showToast({
										title: '保存成功',
										icon: 'success'
									});
								},
								fail: (err) => {
									console.error('保存失败:', err);
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									});
								}
							});
						},
						fail: (err) => {
							console.error('下载图片失败:', err);
						}
					});
				});

				return;
				const systemInfo = uni.getSystemInfoSync();

				// 检查权限
				if (systemInfo.platform === 'android') {
					// 检查存储权限
					const auth = await this.checkStoragePermission();
					if (!auth) {
						uni.showModal({
							title: '权限提示',
							content: '需要存储权限才能保存图片到相册，请在设置中开启',
							confirmText: '去设置',
							success: (res) => {
								if (res.confirm) {
									// 打开应用设置页面
									if (plus && plus.runtime) {
										plus.runtime.openURL('package:' + plus.runtime.appid);
									}
								}
							}
						});
						return;
					}
				}

				if (systemInfo.platform === 'android') {
					// 安卓系统：将blob URL转换为临时文件
					await this.saveImageForAndroid();
				} else {
					// iOS系统：直接保存
					uni.saveImageToPhotosAlbum({
						filePath: this.posterImageUrl,
						success: () => {
							uni.showToast({ title: '保存成功', icon: 'success' });
						},
						fail: (err) => {
							console.error('保存失败:', err);
							uni.showToast({ title: '保存失败，请检查权限', icon: 'none' });
						}
					});
				}
			} catch (error) {
				console.error('保存图片错误:', error);
				uni.showToast({ title: '保存失败', icon: 'none' });
			}
			// #endif
		},

		// 检查存储权限
		checkStoragePermission() {
			return new Promise((resolve) => {
				// #ifdef APP-PLUS
				if (plus && plus.android) {
					const main = plus.android.runtimeMainActivity();
					const Context = plus.android.importClass('android.content.Context');
					const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
					const permission = 'android.permission.WRITE_EXTERNAL_STORAGE';

					const granted = main.checkSelfPermission(permission) === PackageManager.PERMISSION_GRANTED;
					resolve(granted);
				} else {
					resolve(true);
				}
				// #endif
				// #ifndef APP-PLUS
				resolve(true);
				// #endif
			});
		},

		// 安卓系统保存图片
		async saveImageForAndroid() {
			try {
				// 将blob URL转换为base64
				const response = await fetch(this.posterImageUrl);
				const blob = await response.blob();

				return new Promise((resolve, reject) => {
					const reader = new FileReader();

					reader.onload = () => {
						const base64 = reader.result;
						const base64Data = base64.split(',')[1]; // 移除base64前缀

						// 生成临时文件路径
						const tempFilePath = `${wx.env.USER_DATA_PATH}/poster_${Date.now()}.png`;

						// 写入临时文件
						uni.getFileSystemManager().writeFile({
							filePath: tempFilePath,
							data: base64Data,
							encoding: 'base64',
							success: () => {
								// 保存到相册
								uni.saveImageToPhotosAlbum({
									filePath: tempFilePath,
									success: () => {
										uni.showToast({ title: '保存成功', icon: 'success' });
										// 删除临时文件
										uni.getFileSystemManager().unlink({
											filePath: tempFilePath,
											fail: () => {}
										});
										resolve();
									},
									fail: (err) => {
										console.error('保存到相册失败:', err);
										uni.showToast({ title: '保存失败，请检查权限', icon: 'none' });
										reject(err);
									}
								});
							},
							fail: (err) => {
								console.error('写入临时文件失败:', err);
								uni.showToast({ title: '保存失败', icon: 'none' });
								reject(err);
							}
						});
					};

					reader.onerror = () => {
						reject(new Error('读取blob失败'));
					};

					reader.readAsDataURL(blob);
				});
			} catch (error) {
				console.error('安卓保存图片错误:', error);
				uni.showToast({ title: '保存失败', icon: 'none' });
				throw error;
			}
		},
		async sharePoster() {
			// 如果还没有生成图片，先生成
			if (!this.posterImageUrl) {
				await this.generatePoster();
			}
			// H5环境
			// if (uni.getSystemInfoSync().platform === 'h5') {
			// 尝试用 Web Share API 分享图片
			// #ifdef H5
			try {
				// 先将 objectUrl 转为 blob，再转为 File
				const response = await fetch(this.posterImageUrl);
				const blob = await response.blob();
				const file = new File([blob], 'poster.png', { type: 'image/png' });

				if (navigator.canShare && navigator.canShare({ files: [file] })) {
					await navigator.share({
						files: [file],
						title: this.shareOptions.title,
						text: this.shareOptions.desc
					});
					uni.showToast({ title: '分享成功', icon: 'success' });
				} else {
					// 不支持文件分享，弹窗展示图片，提示长按保存
					this.showPosterImage = true;
					uni.showToast({ title: '请长按图片保存后自行分享', icon: 'none' });
				}
			} catch (e) {
				// 兜底：复制链接
				uni.setClipboardData({
					data: this.shareOptions.link,
					success: () => {
						uni.showToast({
							title: '链接已复制，请粘贴分享',
							icon: 'none'
						});
					}
				});
			}
			// #endif
			// } else {
			// 非H5环境，使用uni.share分享图片
			// #ifndef H5
			uni.share({
				provider: 'weixin',
				scene: 'WXSceneSession',
				type: 2, // 2为图片
				imageUrl: this.posterImageUrl,
				success: () => {
					uni.showToast({ title: '分享成功' });
				}
			});
			// #endif
			// }
		}
	}
};
</script>

<style lang="scss" scoped>
/* 全局样式 */
.promotion-container {
	padding: 20rpx 26rpx;
}

/* 规则部分样式 */
.rules-warps {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 36rpx 32rpx 0rpx 32rpx;
	margin-bottom: 20rpx;
}

.rules-section {
	padding-bottom: 40rpx;
}

.section-title {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 500;
	font-size: 32rpx;
	color: #ff7937;
	margin-bottom: 15rpx;
	padding-bottom: 34rpx;
	border-bottom: 2rpx solid #ff7937;
}

.rule-item {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 30rpx;
	color: #666666;
	line-height: 54rpx;
	letter-spacing: 2rpx;
}

.rule-number {
}

.rule-text {
	font-size: 30rpx;
	color: #666;
	flex: 1;
	line-height: 54rpx;
	letter-spacing: 1px;
}

/* 推广成员列表样式 */
.member-title {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-weight: 500;
	font-size: 32rpx;
	color: #0b1f20;
	line-height: 54rpx;
}

.member-list {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 32rpx 32rpx 44rpx 32rpx;
	margin-bottom: 180rpx;
}

.member-item {
	padding: 24rpx 0;
	border-bottom: 2rpx solid #eeeeee;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.member-item:last-child {
	border-bottom: none;
}

.member-info {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
}

.member-header {
	width: 72rpx;
	height: 72rpx;
	background-color: #999999;
	border-radius: 50%;
	margin-right: 20rpx;
}

.member-name,
.member-phone {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 30rpx;
	color: #0b1f20;
	line-height: 54rpx;
}

.member-status {
	/* font-size: 28rpx;
    color: #09bb07; */
}

.member-fee {
	text-align: right;
}

.member-fee-value {
	font-family: DINPro, DINPro;
	font-weight: 500;
	font-size: 36rpx;
	color: #ff7937;
}

.member-fee-value text {
	font-size: 24rpx;
}

.member-fee-label {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 24rpx;
	color: #999999;
	line-height: 54rpx;
}

/* 底部按钮样式 */
.action-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	justify-content: space-between;
	padding: 12rpx 0 14rpx 0;
	background-color: #fff;
}

.action-btn {
	flex: 1;
	text-align: center;
}

.action-btn::after {
	border: none;
}

.action-btn image {
	width: 80rpx;
	height: 80rpx;
	margin-bottom: 10rpx;
}

.action-btn-label {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 26rpx;
	color: #697592;
	line-height: 40rpx;
}

.popup-container {
	position: fixed;
	top: -100%;
	// top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	transition: all 0.3s ease;
	margin: 0 76rpx;
}

.popup-content {
	width: 100%;
	min-height: 1040rpx;
	background-image: url('~@/static/personalCenter/posters.png');
	background-size: 100% 100%;
	background-position: 50% 50%;
	background-repeat: no-repeat;
}

.code-container {
}

.qr-code-warps {
	width: 240rpx;
	height: 240rpx;
	background: #ff7937;
	border-radius: 16rpx 16rpx 16rpx 16rpx;
	position: absolute;
	bottom: 172rpx;
	left: 30%;
	display: flex;
	justify-content: center;
	align-items: center;

	image {
		width: 200rpx;
		height: 200rpx;
	}
}

.tips {
	font-family: Source Han Sans CN, Source Han Sans CN;
	font-size: 30rpx;
	color: #ff7937;
	text-align: center;
	position: absolute;
	left: 18%;
	bottom: 62rpx;
}

.poster-image-popup {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 9999;
}

.popup-actions {
	margin-top: 20rpx;
	display: flex;
	gap: 20rpx;
}

.popup-tip {
	color: #fff;
	margin-top: 10rpx;
	font-size: 24rpx;
}

.poster-image-popup {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	z-index: 9999;
}

.popup-actions {
	margin-top: 20rpx;
	display: flex;
	gap: 20rpx;

	.popup-actions-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 500;
		font-size: 28rpx;
		color: #666666;
		width: 200rpx;
		height: 64rpx;
		background: #f5f5f6;
		border-radius: 36rpx 36rpx 36rpx 36rpx;
	}
}

.popup-tip {
	color: #fff;
	margin-top: 10rpx;
	font-size: 24rpx;
}
</style>